package drawables;

import java.awt.Graphics;
import java.util.ArrayList;

import javafx.scene.canvas.GraphicsContext;
import objects.Track;

import objects.TrackLine;

public class DrawableManager {
	
	// ----- singletone. -----
	static DrawableManager dm=new DrawableManager();
	
	private DrawableManager(){
		drawables = new ArrayList<Drawable>();
		toAdd = new ArrayList<Drawable>();
		toRemove = new ArrayList<Drawable>();
		
		tl = new TrackLine();
	}
	
	static public DrawableManager get(){
		return dm;
	}
	
	
	// -----------------------
	
	private ArrayList<Drawable> drawables;
	private ArrayList<Drawable> toAdd;
	private ArrayList<Drawable> toRemove;
	
	
	private TrackLine tl;
	
	
	private Object aLock = new Object();
	private Object rLock = new Object();
	
	
	public void add(Drawable d){
            synchronized(aLock){
                    toAdd.add(d);
            }
	}
	
	public void remove(Drawable d){
            synchronized (rLock) {
                    toRemove.add(d);
            }
	}
	
	public void paint(Graphics g){
		
            synchronized (aLock) {
                synchronized (rLock) {
                    drawables.addAll(toAdd);
                    drawables.removeAll(toRemove);

                    toAdd.clear();
                    toRemove.clear();
                }
            }

            for(Drawable d : drawables){
                d.paint(g);
            }
            tl.paint(g);
	}
	
        public void paint(GraphicsContext g){
		
		synchronized (aLock) {
			synchronized (rLock) {
				
				drawables.removeAll(toRemove);
				drawables.addAll(toAdd);
				toAdd.clear();
				toRemove.clear();
			}
		}
		
		for(Drawable d : drawables){
			d.paint(g);
		}
		tl.paint(g);
	}

	public Drawable getDrawable(int x, int y) {
		Drawable res = null;
		for(Drawable d : drawables){
			if(d.contains(x, y))
				res = d;
		}
		
		return res;
	}
        
        public Track getTrack(int x, int y){
            Drawable res = null;
		for(Drawable d : drawables){
			if(d.contains(x, y) && d.getType()==Type.TRACK)
				res = d;
		}
		
		return (Track)res;
        }
	
	public TrackLine getTrackLine() {
		return tl;
	}
}
